package com.book.bigwork.Webservice;

import com.book.bigwork.model.Book;
import com.book.bigwork.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    private final BookRepository bookRepository;
    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }
    public List<Book> findAllBooks() {//查找所有图书
        return bookRepository.findAll();
    }
    public Book findBookById(Long bookId) {//查找指定图书
        return bookRepository.findById(bookId).get();
    }
    public Book updateBook(Book book) {//更新图书
        return bookRepository.save(book);
    }
    public void deleteBook(Book book) {//删除图书
        bookRepository.delete(book);
    }
    public List<Book> searchBooks(String query){
        return bookRepository.searchBooks("%"+query+"%");
    }
    public Book saveBook(BookForm bookForm) {//新增图书
        byte[] image = null;
        byte[] imagebackup = null;
        final Book editBook;
        Book book = new Book();
        if (bookForm.getBookImage() != null) {
            try {
                image = bookForm.getBookImage().getBytes();
            } catch (IOException e) {}
            if (image != null && image.length >0) {
                book.setBookImage(image);
                book.setBookImageContentType("image/jpeg");
            }
        }else {
            if (bookForm.getBookId() != null) {
                editBook = bookRepository.findById(bookForm. getBookId()).
                        get();
                imagebackup =editBook.getBookImage();
                book.setBookImage(imagebackup);
                book.setBookImageContentType("image/jpeg");
            }
        }
        book = bookForm.toBook(book);
        return bookRepository.save(book);
    }
}